const express = require("express");
const user = require("./router/user");
const userControl = require("./router/userControl");
const roleControl = require("./router/roleControl");
const menuControl = require("./router/menuControl");
const bodyParser = require("body-parser");
const { verify } = require("./utils/jwt");
require("express-async-errors");

const app = express();

// 获取解析信息
app.use(bodyParser.json());

// jwt解密
app.use(function (req, res, next) {
  verify(req, res, next);
});

// 错误处理
app.use(function (err, req, res, next) {
  console.log("=====================》err:", err);
  if (err.status === 401) {
    console.log("token Invalid");
    return res.json({ code: 401, message: "token Invalid" });
  }
  if (err.message.indexOf("BadRequestError") !== -1) {
    return res.json({ code: 400, message: err.message.split("#")[1] });
  }
  return res.json({ code: 500, message: "服务器异常" });
});

// 用户信息路由
app.use("/admin/acl/index", user);
app.use("/admin/acl/user", userControl);
app.use("/admin/acl/role", roleControl);
app.use("/admin/acl/menu", menuControl);

// 端口设置
app.listen(8889, function () {
  console.log("server 启动");
});
